package com.tim.app.ui.activity.message;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.smarttab.SmartTabLayout;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.tim.app.R;
import com.tim.app.constant.EventTag;
import com.tim.app.db.dao.DaoFactory;
import com.tim.app.server.logic.UserManager;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.UserFriendActivity;
import com.tim.app.ui.adapter.TabAdapter;
import com.tim.app.ui.fragment.message.MessageFragment;
import com.tim.app.ui.fragment.message.NoticeContainerFragment;


/**
 * 消息页面
 */
public class MessageActivity extends BaseActivity implements SmartTabLayout.TabProvider {

    public static final String TAG = "MessageActivity";

    private ImageButton ibBack;
    private ImageView ivContacts;

    private ViewPager vpMyViewContent;
    private TabAdapter pageAdapter;

    private SmartTabLayout viewPagerTab;

    public static void start(Context context) {
        Intent intent = new Intent(context, MessageActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_message;
    }


    @Override
    public void initView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        ibBack = (ImageButton) findViewById(R.id.ibBack);
        ivContacts = (ImageView) findViewById(R.id.ivContacts);
        vpMyViewContent = (ViewPager) findViewById(R.id.vpMyViewContent);

        ibBack.setOnClickListener(this);
        ivContacts.setOnClickListener(this);
        pageAdapter = new TabAdapter(getSupportFragmentManager());
        pageAdapter.addFragment(new NoticeContainerFragment(), getString(R.string.notice));
        pageAdapter.addFragment(new MessageFragment(), getString(R.string.message));
        vpMyViewContent.setOffscreenPageLimit(2);
        vpMyViewContent.setAdapter(pageAdapter);
        vpMyViewContent.setCurrentItem(0);

        viewPagerTab = (SmartTabLayout) findViewById(R.id.tab_layout);
        viewPagerTab.setCustomTabView(this);

        viewPagerTab.setViewPager(vpMyViewContent);

        viewPagerTab.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    setNoticeViewState(View.INVISIBLE);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        EventManager.ins().registListener(EventTag.ON_NEW_NOTICE, eventListener);
        EventManager.ins().registListener(EventTag.ON_READ_MESSAGE_COUNT, eventListener);
        EventManager.ins().registListener(EventTag.ON_NOTICE_MESSAGE_STATED_CHANGED,eventListener);
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_NEW_NOTICE:
                    getUnreadNotice();
                    break;
                case EventTag.ON_READ_MESSAGE_COUNT:
                    int count = (int) dataobj;
                    if (count > 0 || UserManager.ins().getUnreadOfficialMessageCount() > 0) {
                        setMessageViewState(View.VISIBLE);
                    } else {
                        setMessageViewState(View.INVISIBLE);
                    }
                    break;
                case EventTag.ON_NOTICE_MESSAGE_STATED_CHANGED:
                    if (vpMyViewContent.getCurrentItem() == 0) {
                        setNoticeViewState(View.INVISIBLE);
                    } else {
                        setNoticeViewState(View.VISIBLE);
                    }
                    break;
            }
        }
    };

    /**
     * 通知的未读状态
     *
     * @param visibility
     */
    private void setNoticeViewState(int visibility) {
        View tab = viewPagerTab.getTabAt(0);
        View mark = tab.findViewById(R.id.custom_tab_notification_mark);
        mark.setVisibility(visibility);
    }

    /**
     * 消息的未读状态
     *
     * @param visibility
     */
    private void setMessageViewState(int visibility) {
        View tab = viewPagerTab.getTabAt(1);
        View mark = tab.findViewById(R.id.custom_tab_notification_mark);
        mark.setVisibility(visibility);
    }

    @Override
    public void initData() {
        showMessageView();
        getUnreadNotice();
    }

    private void getUnreadNotice() {
        if (DaoFactory.getNoticeDao().getUnReadMessageCount() > 0) {
            if (vpMyViewContent.getCurrentItem() == 0) {
                setNoticeViewState(View.INVISIBLE);
            } else {
                setNoticeViewState(View.VISIBLE);
            }
        } else {
            setNoticeViewState(View.INVISIBLE);
        }
    }

    /**
     * 消息的view
     */
    private void showMessageView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final int unReadMessageTotalCount = NIMClient.getService(MsgService.class).getTotalUnreadCount();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        EventManager.ins().sendEvent(EventTag.ON_READ_MESSAGE_COUNT, 0, 0, unReadMessageTotalCount);
                    }
                });
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.ON_NEW_NOTICE, eventListener);
        EventManager.ins().removeListener(EventTag.ON_READ_MESSAGE_COUNT, eventListener);
        EventManager.ins().removeListener(EventTag.ON_NOTICE_MESSAGE_STATED_CHANGED,eventListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack://返回
                finish();
                break;
            case R.id.ivContacts:
                UserFriendActivity.start(this);
                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public View createTabView(ViewGroup container, int position, PagerAdapter adapter) {
        LayoutInflater inflater = LayoutInflater.from(container.getContext());
        Resources res = container.getContext().getResources();
        View tab = inflater.inflate(R.layout.message_tab_icon, container, false);
        View mark = tab.findViewById(R.id.custom_tab_notification_mark);
        mark.setVisibility(View.INVISIBLE);
        TextView value = (TextView) tab.findViewById(R.id.custom_text);
        switch (position) {
            case 0:
                value.setText(res.getString(R.string.notice));
                break;
            case 1:
                value.setText(res.getString(R.string.message));
                break;
        }
        return tab;
    }
}
